/**
 * Created by PanJiaChen on 16/11/18.
 */
import { v4 as uuidv4 } from 'uuid'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

//校验密码强度---沒有匹配到以下級別就提示
export function checkPwdStrength(value) {
  // 0： 表示第一个级别 1：表示第二个级别 2：表示第三个级别 3： 表示第四个级别 4：表示第五个级别
  var arr = [],
    array = [1, 2, 3, 4]
  if (value.length < 6) {
    //最初级别
    return 0
  }
  if (/\d/.test(value)) {
    //如果用户输入的密码 包含了数字
    arr.push(1)
  }
  if (/[a-z]/.test(value)) {
    //如果用户输入的密码 包含了小写的a到z
    arr.push(2)
  }
  if (/[A-Z]/.test(value)) {
    //如果用户输入的密码 包含了大写的A到Z
    arr.push(3)
  }
  if (/\W/.test(value)) {
    //如果是非数字 字母 下划线
    arr.push(4)
  }
  for (var i = 0; i < array.length; i++) {
    if (arr.indexOf(array[i]) == -1) {
      return array[i]
    }
  }
}

// 隐藏字号
export function hideCharacter(value, type) {
  if (typeof value != 'string' && typeof value != 'number') return
  if (type === 'phone') return value.substring(0, 3) + '****' + value.substr(value.length - 4)
  if (type === 'email') {
    if (String(value).indexOf('@') > 0) {
      let str = value.split('@'),
        _s = ''

      if (str[0].length > 3) {
        for (let i = 0; i < str[0].length - 3; i++) {
          _s += '*'
        }
      }
      return str[0].substr(0, 1) + _s + '@' + str[1]
    }
  }
}

export function getUuid() {
  return uuidv4()
}

export function download_url(name, url, type = 'vnd.ms-excel') {
  let blob = new Blob([url], {
    type: `application/${type};charset=utf-8`
  })
  // console.log(blob, 'blob')
  // FileReader主要用于将文件内容读入内存
  let reader = new FileReader()
  reader.readAsDataURL(blob)
  // onload当读取操作成功完成时调用
  reader.onload = function (e) {
    let a = document.createElement('a')
    // 获取文件名fileName
    a.download = name
    a.href = e.target.result
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }
}
